<template>

<h1>图书列表</h1>
<input type="text" placeholder="请输入关键字" v-model="keyword">
<input type="button" value="查询" @click="btnfilter">
<input type="button" value="新增" @click="btnadd">
    <table>
        <thead>
            <tr>
                <th>序号</th>
                <th>书名</th>
                <th>作者</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="book in books" :key="book.id">
                <td>{{ book.id }}</td>
                <td>{{ book.bookName }}</td>
                <td>{{ book.author }}</td>
                <td>
                    <input type="button" value="编辑" @click="btnedit(book.id)">
                    <input type="button" value="删除" @click="btndel(book.id)">
                </td>
            </tr>
        </tbody>
    </table>
</template>

<script setup>
import { onMounted, reactive,ref } from 'vue';
import { delItem, getAll } from '@/api/bookapi';
import {useRouter} from 'vue-router';

const router = useRouter()
// ==响应式数据-开始==
let books = reactive([])
let keyword = ref('')
//==响应式数据-结束==


//==生命周期函数--初始数据==
onMounted(async ()=>{
    let data = await getAll()
    books.push(...data.data)
})

// ==生命周期函数-结束==

// ==功能实现-开始==
//删除功能，调用delItem()函数
async function btndel(id){
    console.log('删除');
        
    if (confirm('确认删除吗？')) {
        let data = await delItem(id)
        if (data.code === 1000) {
            console.log(data.msg);
            let index = books.findIndex(item=>item.id === id)
            books.splice(index,1)
        
        }else{
            console.log(data.msg);        
        }
        
    }
}

//新增功能
function btnadd(){
    console.log('新增');
    router.push('/bookadd')

}

//编辑功能
function btnedit(id){
    console.log('编辑');
    router.push(`/bookedit/${id}`)
}

//查询功能
async function btnfilter(){
    const trimkeyword = keyword.value.trim()
    let data = await getAll(trimkeyword)

    //先移除所有数据，再响应
    books.splice(0)
    books.push(...data.data)
}

// ==功能实现-结束==
</script>
